package com.hx.vending.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.vending.annotation.AnnotationField;
import com.hx.vending.annotation.Authorization;
import com.hx.vending.annotation.CurrentFieldId;
import com.hx.vending.annotation.CurrentUserId;
import com.hx.vending.bean.Equipment;
import com.hx.vending.bean.Field;
import com.hx.vending.bean.config.Constants;
import com.hx.vending.service.IEquipmentService;
import com.hx.vending.service.IFieldService;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/field")
public class FieldController {

    @Autowired
    private IFieldService fieldService;
    @Autowired
    private IEquipmentService equipmentService;

    /*
   * 添加场地
   * */
    @RequestMapping(value = "/saveField")
    @ResponseBody
    @Authorization
    public Msg saveField(@RequestBody Field field,@CurrentUserId Integer userId,BindingResult result){
        if(result.hasErrors()){
            //校验失败，应该返回失败，在模态框中显示校验失败的错误信息
            Map<String, Object> map = new HashMap<String, Object>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
              /*  System.out.println"错误的字段名："+fieldError.getField());
                System.out.println("错误信息："+fieldError.getDefaultMessage());*/
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        }else{
            field.setFieldUserId(userId);
            if(field.getFieldDefault().equals(1)){
                Field field1 =  new Field();
                field1.setFieldUserId(field.getFieldUserId());
                List<Field> list = fieldService.selectByExample(field1);
                if(list.size() > 0){
                    for(Field f:list){
                        f.setFieldDefault(0);
                        fieldService.updateByPrimaryKeySelective(f);
                    }
                }
            }
            int i = fieldService.insertSelective(field);
            if(i != 0){
                return Msg.success().add("va_msg","设置成功");
            }else{
                return Msg.fail();
            }
        }
    }

    /*
   *查询商家所有投放地址
   * */
    @RequestMapping("/getFieldByUser")
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg getFieldByUser(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                              @CurrentUserId Integer userid,@CurrentFieldId Integer[] integers){
        PageHelper.startPage(pageNum, pageSize);
        if(ToolUtil.isNotEmpty(userid)){
            List<Field> list = fieldService.selectFieldById(integers);
            for(Field f:list){
                List<Equipment> equipmentList = equipmentService.selectByFieldId(f.getFieldId());

                f.setNum(equipmentList.size());
            }
            PageInfo page = new PageInfo(list, 5);
            return Msg.success().add("pageInfo", page).add("fieldNum",list.size());
        }else{
            return Msg.fail().add("va_msg","用户未登录");
        }
    }


    /**
     * 根据ID查询
     * @param
     * @return
     */
    @RequestMapping(value="/getFieldById/{id}",method= RequestMethod.GET)
    @ResponseBody
    @Authorization
    public Msg getFieldById(@PathVariable("id")Integer id){
        Field field = new Field();
        field.setFieldId(id);
        Field f = fieldService.selectByPrimary(field);
        if(ToolUtil.isNotEmpty(f)){
            return Msg.success().add("field",f);
        }else{
            return Msg.fail().add("va_msg", "未找到该投放地址信息");
        }
    }

    /*
    * 修改场地
    * */
    @ResponseBody
    @RequestMapping(value="/updateField",method=RequestMethod.POST)
    @Authorization
    public Msg updateField(@RequestBody Field field){
        if(field.getFieldDefault().equals(1)){
            Field field1 =  new Field();
            field1.setFieldUserId(field.getFieldUserId());
            List<Field> list = fieldService.selectByExample(field1);
            if(list.size() > 0){
                for(Field f:list){
                    f.setFieldDefault(0);
                    fieldService.updateByPrimaryKeySelective(f);
                }
            }
        }
        int result = fieldService.updateByPrimaryKeySelective(field);
        if(result != 0){
            return Msg.success();
        }else{
            return Msg.fail();
        }

    }

    /**
     * 修改为默认
     */
    @ResponseBody
    @RequestMapping(value="/updateFieldByDefault")
    @Authorization
    public Msg updateFieldByDefault(@RequestParam Integer fieldid){
        Field field = new Field();
        field.setFieldId(fieldid);
        Field fl = fieldService.selectByPrimary(field);
        if (ToolUtil.isNotEmpty(fl)) {
            Field fil = new Field();
            fil.setFieldUserId(fl.getFieldUserId());
            List<Field> list = fieldService.selectByExample(fil);
            for(Field f:list){
                if(f.getFieldId().equals(fl.getFieldId())){
                    //设为默认
                    f.setFieldDefault(1);
                }else{
                    f.setFieldDefault(0);
                }
                fieldService.updateByPrimaryKeySelective(f);
            }
            return Msg.success();
        } else {
            return Msg.fail();
        }
    }

    /**
     * 单个批量二合一
     * 批量删除：1-2-3
     * 单个删除：1
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/deleteField/{ids}",method=RequestMethod.DELETE)
    @Authorization
    public Msg deleteField(@PathVariable String ids){
        //批量删除
        if(ids.contains("-")){
            String[] str_ids = ids.split("-");
            for(int i = 0;i < str_ids.length;i++){
                Integer id = Integer.parseInt(str_ids[i]);
                Equipment equipment = new Equipment();
                equipment.setEquipmentFieldId(id);
                List<Equipment> list = equipmentService.selectByExample(equipment);
                if(list.size() > 0){
                    return Msg.fail().add("msg","场地不能删除");
                }
                fieldService.deleteByPrimaryKey(id);
            }
        }else{
            Integer id = Integer.parseInt(ids);
            Equipment equipment = new Equipment();
            equipment.setEquipmentFieldId(id);
            List<Equipment> list = equipmentService.selectByExample(equipment);
            if(list.size() > 0){
                return Msg.fail().add("msg","场地不能删除");
            }
            fieldService.deleteByPrimaryKey(id);
        }
        return Msg.success().add("msg","删除成功");
    }
    /*
    * 获取场地收益列表
    * */
    @ResponseBody
    @RequestMapping(value = "/getFieldListByUserId",method = RequestMethod.POST)
    @Authorization
    @AnnotationField
    public Msg getFieldListByUserId(@RequestBody Map<String,Object> paramMap, @CurrentUserId Integer userId, @CurrentFieldId Integer[] integers){
        return fieldService.getFieldListByUserId(paramMap,userId,integers);
    }

    /**
     * 查询商户下所有场地
     * @param
     * @return
     */
    @RequestMapping("/selectAllFieldByUserId")
    @ResponseBody
    @Authorization
    @AnnotationField
    public Msg selectAllFieldByUserId(@CurrentFieldId Integer[] integers ){
        try{
            List<Field> fieldList = fieldService.selectFieldById(integers);
            return Msg.success().add("fieldList",fieldList);
        }catch (Exception e){
            return Msg.fail();
        }

    }

}
